package com.kms.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jcraft.jsch.JSchException;
import com.kms.console.JSchConsole;
import com.kms.derby.Connections;
import com.kms.model.MGroup;
import com.kms.model.MSyspara;
import com.kms.model.SystemParameterBean;
import com.kms.service.SystemparameterService;
import com.kms.util.CoreUtil;




public class SystemSettingServlet extends HttpServlet {
	SystemparameterService sysservice ;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		sysservice = (SystemparameterService)Connections.getServiceBean(request, "sysparaService");
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		sysservice = (SystemparameterService)Connections.getServiceBean(request, "sysparaService");
		
		String status = request.getParameter("status1");
		request.setAttribute("status1", status);
		String[] mgid = request.getParameterValues("mgid");
		if("sysinsert".equals(status)){
			request.getRequestDispatcher("editsystemparameter.jsp").forward(request,response); 
			return;
		}else if("sysupdate".equals(status)){
			if(mgid!=null && mgid.length>=1){
				request.setAttribute("mgroup", sysservice.selectmGroup(mgid[0]));
				request.getRequestDispatcher("editsystemparameter.jsp").forward(request,response); 
				return;
			}
		}else if("sysselect".equals(status)|| "sysupdate".equals(status)){
			if(mgid!=null && mgid.length>=1){
				request.setAttribute("sysselect", "sysselect");
				request.setAttribute("mgroup", sysservice.selectmGroup(mgid[0]));
				request.getRequestDispatcher("editsystemparameter.jsp").forward(request,response); 
				return;
			}
		}else if("sysdelete".equals(status)){
			if(mgid!=null && mgid.length>=1){
				for(String mgid2:mgid){
					//delete
					sysservice.deletemGroup(mgid2);
					sysservice.deleteSyspara(mgid2);
					
					//rm linux dir
					MGroup mgroup = sysservice.selectmGroup(mgid2);
					if(mgroup!=null && mgroup.getListsyspara()!=null)
					for(MSyspara msys:mgroup.getListsyspara()){
						rmlinux(msys);
					}
				}
			}
		}else if("sysinserteditview".equals(status)){
			this.insertSystempara(request);
		}else if("sysupdateeditview".equals(status)){
			this.updatesyspara(request);
		}else {
			this.getSysSetting(request);
		}
		request.setAttribute("listmgroup",  sysservice.selectAllMGroup());
		request.getRequestDispatcher("systemparameter.jsp").forward(request,response); 
	}
	
	public void updatesyspara(HttpServletRequest request){
		MGroup mgroup = getMGroup(request);
		MSyspara msyspara = getMsyspara("msyspara",request);
		MSyspara msysdb = getMsyspara("msysdb",request);
		mgroup.setId(request.getParameter("mgid"));
		
		msyspara.setMgid(request.getParameter("mgid"));
		msyspara.setId(Integer.valueOf(request.getParameter("appid")));
		
		msysdb.setMgid(request.getParameter("mgid"));
		msysdb.setId(Integer.valueOf(request.getParameter("dbid")));
		sysservice.updatemGroup(mgroup);
		sysservice.updateSyspara(msyspara);
		sysservice.updateSyspara(msysdb);
		
		mkdirlinux(mgroup,msyspara,msysdb);
	}
	
	
	public void insertSystempara(HttpServletRequest request){
		String seq_mgroup = CoreUtil.getUUIDJDK();
		MGroup mgroup = getMGroup(request);
		MSyspara msyspara = getMsyspara("msyspara",request);
		MSyspara msysdb = getMsyspara("msysdb",request);
		mgroup.setId(seq_mgroup);
		msyspara.setMgid(seq_mgroup);
		msysdb.setMgid(seq_mgroup);
		sysservice.insertmGroup(mgroup);
		sysservice.insertSyspara(msyspara);
		sysservice.insertSyspara(msysdb);
		
		mkdirlinux(mgroup,msyspara,msysdb);
	}
	
	public void Systempara(){
		
	}
	
	public MSyspara getMsyspara(String systype,HttpServletRequest request){
		MSyspara msys = new MSyspara();
		if("msyspara".equals(systype)){
			msys.setDatatype("APP");
			msys.setOsip(request.getParameter("app_osip"));
			msys.setTbsmonitorosip(request.getParameter("app_tbsmonitor_osip"));
			msys.setOsport(request.getParameter("app_osport"));
			msys.setOsuser(request.getParameter("app_osuser"));
			msys.setOspwd(request.getParameter("app_ospwd"));
			msys.setLogzipdir(request.getParameter("app_logzipdir"));
			msys.setLogdir(request.getParameter("app_logdir"));
			msys.setDbzipdir(request.getParameter("app_dbzipdir"));
			msys.setMonitorlogdir(request.getParameter("app_monitorlogdir"));
			msys.setMonitorserverurl(request.getParameter("app_monitorserverurl"));
		}else if("msysdb".equals(systype)){
			msys.setDatatype("DB");
			msys.setDbzipdir(request.getParameter("db_dbzipdir"));
			msys.setOsip(request.getParameter("db_osip"));
			msys.setOsport(request.getParameter("db_osport"));
			msys.setOsuser(request.getParameter("db_osuser"));
			msys.setOspwd(request.getParameter("db_ospwd"));
			msys.setKmsuser(request.getParameter("db_kmsuser"));
			msys.setKmspwd(request.getParameter("db_kmspwd"));
			msys.setBonduser(request.getParameter("db_bonduser"));
			msys.setBondpwd(request.getParameter("db_bondpwd"));
			msys.setKmsinstance(request.getParameter("db_kmsinstance"));
			msys.setBondinstance(request.getParameter("db_bandinstance"));
			msys.setKmsdirectory(request.getParameter("db_kmsdirectory"));
			msys.setKmsdirectorypath(request.getParameter("db_kmsdirectorypath"));
			msys.setBonddirectory(request.getParameter("db_bonddirectory"));
			msys.setBonddirectorypath(request.getParameter("db_bonddirectorypath"));
		}
		msys.setLastmodified(new Date());
		return msys;
	}
	
	public MGroup getMGroup(HttpServletRequest request){
		MGroup mgroup = new MGroup();
		mgroup.setName(request.getParameter("mname"));
		mgroup.setCname(request.getParameter("mcname"));
		mgroup.setLastmodified(new Date());
		return mgroup;
	}
	
	private void getSysSetting(HttpServletRequest request){
		List<SystemParameterBean> listsysbean = new ArrayList<SystemParameterBean>();
		try {
			Connection conn = Connections.getConnection(request);
			String SQL = "SELECT * FROM SYSSETTING";
			PreparedStatement stmt = conn.prepareStatement(SQL);
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				String id = rs.getInt("Id")+"";
				if(request.getParameter(id)!=null){
					SQL = "update syssetting set value='"+request.getParameter(id)+"' where id="+id+"";
					stmt = conn.prepareStatement(SQL);
					stmt.execute();
				}
			}
			
			SQL = "SELECT * FROM SYSSETTING";
			stmt = conn.prepareStatement(SQL);
			rs = stmt.executeQuery();
			listsysbean.clear();
			while (rs.next()) {
				SystemParameterBean sysb = new SystemParameterBean();
				sysb.setId(rs.getInt("Id"));
				sysb.setName(rs.getString("Name"));
				sysb.setType(rs.getString("Type"));
				sysb.setValue(rs.getString("Value"));
				sysb.setEnabled(rs.getString("Enabled"));
				sysb.setDescription(rs.getString("Description"));
				listsysbean.add(sysb);
			}
			
			rs.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		request.setAttribute("listsysbean", listsysbean);
	}
	
	/**
	 * mkdir dir
	 * @param request
	 */
	private void mkdirlinux(MGroup mgroup,MSyspara msyspara,MSyspara msysdb){
		try {
			JSchConsole jc = new JSchConsole();	
			String host = msyspara.getOsip();
			String user = msyspara.getOsuser();
			String pwd =  msyspara.getOspwd();
			String command = "";
			int port = 0;
			try{
				port = Integer.parseInt(msyspara.getOsport());
			}catch(Exception ex){}
			command = "mkdir "+msyspara.getLogzipdir();
			//mk dir logzipdir
			jc.sshExecute(host, user, pwd, command, port);
			//chmod dir
			command = "chmod "+msyspara.getLogzipdir()+" 755";
			jc.sshExecute(host, user, pwd, command, port);
			
			command = "mkdir "+msyspara.getMonitorlogdir();
			//mk dir logzipdir
			jc.sshExecute(host, user, pwd, command, port);
			//chmod dir
			command = "chmod "+msyspara.getMonitorlogdir()+" 755";
			jc.sshExecute(host, user, pwd, command, port);
			
			command = "mkdir "+msysdb.getDbzipdir();
			//mk dir logzipdir
			jc.sshExecute(host, user, pwd, command, port);
			//chmod dir
			command = "chmod "+msysdb.getDbzipdir()+" 755";
			jc.sshExecute(host, user, pwd, command, port);
			
		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Rm -r dir
	 * @param request
	 */
	private void rmlinux(MSyspara msyspara){
		try {
			JSchConsole jc = new JSchConsole();	
			String host = msyspara.getOsip();
			String user = msyspara.getOsuser();
			String pwd =  msyspara.getOspwd();
			String command = "";
			int port = 0;
			try{
				port = Integer.parseInt(msyspara.getOsport());
			}catch(Exception ex){}
			command = "rm -r "+msyspara.getLogzipdir();
			//rm dir logzipdir
			jc.sshExecute(host, user, pwd, command, port);
			
			command = "rm -r "+msyspara.getMonitorlogdir();
			//rm dir logzipdir
			jc.sshExecute(host, user, pwd, command, port);
			
			command = "rm -r "+msyspara.getDbzipdir();
			//rm dir logzipdir
			jc.sshExecute(host, user, pwd, command, port);
			
		} catch (JSchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
